<?php

namespace App\Service\Outside\FileTranscoding;

use App\Service\BaseService;
use App\Service\Common\OssService;
use App\Service\Common\UploadTranscoding;
use Illuminate\Http\Request;
use Kuafu\File\FileUtil;
use OSS\Core\OssException;

class FileTranscodingService extends BaseService
{
    /**
     * @param Request $request
     * @return array
     * @throws OssException
     */
    public static function imageToWebp(Request $request): array
    {
        $key          = "image_webp";
        $uploadedFile = $request->file('file');
        $suffix       = FileUtil::guessSuffix($uploadedFile->getClientOriginalName());
        $ossInfo      = OssService::uploadFile($uploadedFile->getRealPath(), $suffix);

        $filePath        = $ossInfo["url"];
        $filePathKey     = trim(parse_url($filePath)["path"], "/");
        $filePathEncoded = vsprintf(
            "%s_%s_encoded.webp", [
                explode(".", $filePathKey)[0],
                $key
            ]
        );

        $jobId = UploadTranscoding::asyncFileTranscoding(
            $filePathKey,
            config("file-transcoding.{$key}"),
            "",
            $filePathEncoded
        );

//        UploadTranscoding::getWorkFile($jobId);

        $parsedUrl = parse_url($filePath);

        $url = vsprintf("%s://%s/%s", [
            $parsedUrl["scheme"],
            $parsedUrl['host'],
            $filePathEncoded
        ]);

        return [
            "url"          => $url,
            "base64Encode" => base64_encode(file_get_contents($url))
        ];
    }
}
